package com.xx566.blog.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.xx566.blog.bean.CacheBean;
import com.xx566.blog.bean.LuceneBean;
import com.xx566.blog.common.XX566Cache;
import com.xx566.blog.common.XX566Cache.CacheKey;
import com.xx566.blog.interceptor.LoginInterceptor;
import com.xx566.blog.model.Article;
import com.xx566.blog.model.Friendly;
import com.xx566.blog.model.Tags;
import com.xx566.blog.model.User;
import com.xx566.blog.utils.LuceneUtil;
import com.xx566.blog.utils.PageUtil;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AdminController extends Controller {

	private static final Logger LOGGER = Logger
			.getLogger(AdminController.class);

	/**
	 * 跳转到登录页面
	 * 
	 * @Title: login
	 * @author Realfighter
	 * @date 2014-6-7 下午04:32:16 void
	 */
	public void login() {
		render("login.jsp");
	}

	/**
	 * 验证登录
	 */
	public void loginToIndex() {
		String username = getPara("name");
		String password = getPara("password");
		String returnUrl = getPara("returnUrl");
		setAttr("returnUrl", returnUrl);
		User user = User.dao.findFirst(
				"select * from user where upper(name)=? and pwd=?",
				new Object[] { username.toUpperCase(), password });
		if (user == null) {
			setAttr("error_info", "用户名或邮箱地址错误");
			render("error.jsp");
		} else if (user.getInt("state") == 1) {
			setSessionAttr("xx566_userid", user.getInt("id"));
			redirect("/admin/artList");
		} else {
			setSessionAttr("xx566_userid", user.getInt("id"));
			redirect("/");
		}
	}

	/**
	 * 跳转到发布页面
	 */
	@Before(LoginInterceptor.class)
	public void toPublish() {
		if (!isParaBlank(0)) {// 文章ID不为空
			setAttr("adminArtID", getParaToInt());
		}
		render("admin.jsp");
	}

	/**
	 * 获取左侧标签树
	 */
	@Before(LoginInterceptor.class)
	public void lefting() {
		List<Tags> tags = CacheKit.get("tags", "tags", XX566Cache
				.getIDataLoaderByKey(CacheKey.tags));
		Map<String, String> map = new HashMap<String, String>();
		List<String> list = new ArrayList<String>();
		int count = 0;
		for (Tags tag : tags) {
			String str = "";
			if (!map.containsKey(tag.getStr("type"))) {
				count--;
				str += "{id:" + count + ",";
				str += "pId:0,";
				str += "name:'" + tag.getStr("type") + "'}";
				map.put(tag.getStr("type"), String.valueOf(count));
				list.add(str);
			}
			str = "{id:" + tag.getLong("id") + ",";
			str += "pId:" + map.get(tag.getStr("type")) + ",";
			str += "name:'" + tag.getStr("name") + "'}";
			list.add(str);
		}
		setAttr("admin_tags", list.toString());
		render("include/left.jsp");
	}

	/**
	 * main页面
	 */
	@Before(LoginInterceptor.class)
	public void centering() {
		if (!isParaBlank(0)) {// 存在文章ID
			setAttr("article_admin", Article.dao.findById(getParaToInt()));
		}
        List<String> list = new ArrayList<String>();
        // 获取upload下面所有的文件名
//        String folder = "upload";
//        File file = new File(PathKit.getWebRootPath() + File.separator + folder);
//        String[] files = file.list();
//		for (String filename : files) {
//			list.add(folder+"/"+filename);
//		}
        //这里不再获取所有上传的图片，修改为获取文章的所有配图
        List<Article> files = Article.dao.findAllArticleImages();
        for (Article article : files) {
            list.add(article.getStr("picture"));
        }
		System.out.println(list.toString());
		setAttr("uploadlist", list);
		render("include/center.jsp");
	}

	/**
	 * header
	 */
	@Before(LoginInterceptor.class)
	public void toping() {
		render("include/top.jsp");
	}

	/**
	 * 创建索引(只生成一次)
	 * 
	 * @Title: generateIndexes
	 * @author Realfighter
	 * @date 2014-6-25 下午01:07:17 void
	 */
	@Before(LoginInterceptor.class)
	public void generateIndexes() {
		String result = "创建文章索引成功";
		List<LuceneBean> articles = Article.dao.findOnline();
		try {
			LuceneUtil.createIndex(articles);
		} catch (Exception e) {
			result = "创建文章索引异常";
			LOGGER.error("创建文章索引异常!" + e);
		}
		renderText(result);
	}

	/**
	 * 发表文章
	 */
	@Before(LoginInterceptor.class)
	public void publish() {
		int artstatus = getParaToInt("admin_status");
		setAttr("afterpublish", "<script>alert('保存成功');</script>");
		Article article = getModel(Article.class);
		// 获取用户ID
		Integer userid = getSessionAttr("xx566_userid");
		article.set("userid", userid);
		// 设置文章默认图片
		// TODO
		/** 创建索引 **/
		LuceneBean luceneBean = null;
		if (artstatus == 10010) {// 标识编辑文章
			article.update();
			// 更新缓存
			CacheKit.put(CacheBean.ARTICLES, CacheBean.ARTICLES, Article.dao
					.findArticles4Page(1, 10, 0, "0-0", userid, false));
			CacheKit.put(CacheBean.ARCHIVE_TIMES, CacheBean.ARCHIVE_TIMES,
					Article.dao.findAllArchiveTimes());
			// 更新索引
			luceneBean = new LuceneBean(article.getInt("id"), article
					.getStr("title"), article.getStr("remark"));
			try {
				LuceneUtil.updateIndex(luceneBean);
			} catch (Exception e) {
				LOGGER.error("更新文章索引异常!" + e);
			}
			redirect("/admin/artList");
		} else {
			article.save();
			// 更新缓存
			CacheKit.put(CacheBean.ARTICLES, CacheBean.ARTICLES, Article.dao
					.findArticles4Page(1, 10, 0, "0-0", userid, false));
			CacheKit.put(CacheBean.ARCHIVE_TIMES, CacheBean.ARCHIVE_TIMES,
					Article.dao.findAllArchiveTimes());
			// 添加索引
			luceneBean = new LuceneBean(article.getInt("id"), article
					.getStr("title"), article.getStr("remark"));
			try {
				LuceneUtil.addIndex(luceneBean);
			} catch (Exception e) {
				LOGGER.error("添加文章索引异常!" + e);
			}
			render("include/center.jsp");
		}
	}

	/**
	 * 文章列表
	 * 
	 * @Title: artList
	 * @author Realfighter
	 * @date 2014-6-17 下午01:22:20 void
	 */
	@Before(LoginInterceptor.class)
	public void artList() {
		// 获取用户ID
		Integer userid = getSessionAttr("xx566_userid");
		int pagenum = 1;
		int pageSize = 20;
		long tagid = 0;// 标签ID
		String time = "0-0";// 默认日期
		if (!isParaBlank(0)) {// 页码
			pagenum = getParaToInt(0);
		}
		Page<Article> page = Article.dao.findArticles4Page(pagenum, pageSize,
				tagid, time, userid, true);
		setAttr("page", new PageUtil(page));
		render("admin_artlist.jsp");
	}

	/**
	 * 删除
	 * 
	 * @Title: artdel
	 * @author Realfighter
	 * @date 2014-6-17 下午03:00:03 void
	 */
	@Before(LoginInterceptor.class)
	public void artdel() {
		int artid = 0;
		if (!isParaBlank(0)) {// 文章ID
			artid = getParaToInt(0);
		}
		// 获取用户ID
		Integer userid = getSessionAttr("xx566_userid");
		User user = User.dao.findFirst("select * from user where id=?", userid);
		String renderString = "网络异常";
		// 校验是否admin用户
		if (user.getStr("name").equalsIgnoreCase("Realfighter")
				&& user.getInt("state") == 1) {
			if (artid > 0) {// 删除
				Article.dao.findById(artid).delete();
				// 更新缓存
				CacheKit.put(CacheBean.ARTICLES, CacheBean.ARTICLES,
						Article.dao.findArticles4Page(1, 10, 0, "0-0", userid,
								false));
				CacheKit.put(CacheBean.ARCHIVE_TIMES, CacheBean.ARCHIVE_TIMES,
						Article.dao.findAllArchiveTimes());
				renderString = "操作成功";
				// 删除索引
				LuceneBean vo = new LuceneBean(artid, null, null);
				try {
					LuceneUtil.deleteIndex(vo);
				} catch (Exception e) {
					renderString = "操作成功，但删除索引异常";
					LOGGER.error("删除文章索引异常!" + e);
				}
			}
		}
		renderText(renderString);
	}

	/**
	 * 标签列表
	 * 
	 * @Title: tagList
	 * @author Realfighter
	 * @throws java.io.UnsupportedEncodingException
	 * @date 2014-6-21 下午03:00:05 void
	 */
	@Before(LoginInterceptor.class)
	public void tagList() {
		int pagenum = 1;
		int pageSize = 20;
		String category = "a";// 默认分类
		if (!isParaBlank(0)) {// 页码
			pagenum = getParaToInt(0);
		}
		Page<Tags> page = null;
		if (!isParaBlank(1) && !getPara(1).equals(category)) {
			try {
				category = URLDecoder.decode(getPara(1), "utf-8");
			} catch (UnsupportedEncodingException e) {
				LOGGER.error("中文转码异常：" + e);
				category = "a";
			}
		}
		List<Tags> cateList = Tags.dao.findCateList();
		setAttr("tags_cateList", cateList);
		setAttr("tag_category", category);
		page = Tags.dao.findTags4Page(pagenum, pageSize, category);
		setAttr("page", new PageUtil(page));
		render("admin_taglist.jsp");
	}

	/**
	 * 编辑标签
	 * 
	 * @Title: tagedit
	 * @author Realfighter
	 * @date 2014-6-21 下午04:31:22 void
	 */
	@Before(LoginInterceptor.class)
	public void tagedit() {
		List<Tags> cateList = Tags.dao.findCateList();
		setAttr("tags_cateList", cateList);
		if (!isParaBlank(0)) {
			int tagid = getParaToInt(0);
			Tags tags = Tags.dao.findById(tagid);
			setAttr("tags_tags", tags);
		}
		render("admin_tagsedit.jsp");
	}

	/**
	 * 保存编辑
	 * 
	 * @Title: savetagedit
	 * @author Realfighter
	 * @date 2014-6-21 下午04:54:40 void
	 */
	@Before(LoginInterceptor.class)
	public void savetagedit() {
		Tags tags = getModel(Tags.class);
		if (tags.getLong("id") == null || tags.getLong("id") == 0) {
			tags.save();
		} else {
			tags.update();
		}
		// 更新缓存
		CacheKit.put(CacheBean.TAGS, CacheBean.TAGS, Tags.dao.findAll());
		CacheKit.put(CacheBean.CATES, CacheBean.CATES, Tags.dao.findCateList());
		renderText("操作成功");
	}

	/**
	 * 删除标签
	 */
	@Before(LoginInterceptor.class)
	public void tagdelete() {
		final int tagid = getParaToInt(0);
		boolean succeed = Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				try {
					// 删除标签
					Tags.dao.deleteById(tagid);
					// 删除标签下所有文章
					Article.dao.deleteByTagid(tagid);
					return true;
				} catch (Exception e) {
					LOGGER.error("标签删除异常：" + e);
				}
				return false;
			}
		});
		if (succeed) {
			// 更新缓存
			CacheKit.put(CacheBean.TAGS, CacheBean.TAGS, Tags.dao.findAll());
			CacheKit.put(CacheBean.CATES, CacheBean.CATES, Tags.dao
					.findCateList());
			renderText("操作成功");
		} else {
			renderText("网络异常");
		}
	}

	/**
	 * 标签管理
	 */
	@Before(LoginInterceptor.class)
	public void linkList() {
		int pagenum = 1;
		int pageSize = 20;
		if (!isParaBlank(0)) {// 页码
			pagenum = getParaToInt(0);
		}
		Page<Friendly> page = Friendly.dao
				.findFriendlys4Page(pagenum, pageSize);
		setAttr("page", new PageUtil(page));
		render("admin_linklist.jsp");
	}

	/**
	 * 跳转到编辑或保存友链
	 */
	@Before(LoginInterceptor.class)
	public void linksedit() {
		if (!isParaBlank(0)) {
			int linksid = getParaToInt(0);
			Friendly friendly = Friendly.dao.findById(linksid);
			setAttr("friendly_friendly", friendly);
		}
		render("admin_linksedit.jsp");
	}

	/**
	 * 编辑或保存友链
	 */
	@Before(LoginInterceptor.class)
	public void savelinksedit() {
		Friendly friendly = getModel(Friendly.class);
		if (friendly.getLong("id") == null || friendly.getLong("id") == 0) {
			friendly.save();
		} else {
			friendly.update();
		}
		// 更新缓存
		CacheKit.put(CacheBean.FRIENDLYS, CacheBean.FRIENDLYS, Friendly.dao
				.findAll());
		renderText("操作成功");
	}

	/**
	 * 删除友链
	 */
	@Before(LoginInterceptor.class)
	public void linksdelete() {
		// 删除标签
		Friendly.dao.deleteById(getParaToInt(0));
		// 更新缓存
		CacheKit.put(CacheBean.FRIENDLYS, CacheBean.FRIENDLYS, Friendly.dao
				.findAll());
		renderText("操作成功");
	}

	/**
	 * 留言列表
	 */
	@Before(LoginInterceptor.class)
	public void msgList() {
		int pagenum = 1;
		int pageSize = 20;
		if (!isParaBlank(0)) {// 页码
			pagenum = getParaToInt(0);
		}
		Page<com.xx566.blog.model.Message> page = com.xx566.blog.model.Message.dao.findMessages4Page(pagenum, pageSize);
		setAttr("page", new PageUtil(page));
		render("admin_msglist.jsp");
	}

	/**
	 * 删除留言
	 */
	@Before(LoginInterceptor.class)
	public void msgdelete() {
		final int msgid = getParaToInt(0);
		boolean succeed = Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				try {
					// 删除留言
					com.xx566.blog.model.Message.dao.deleteById(msgid);
					// 删除留言下所有回复
					com.xx566.blog.model.Message.dao.deleteByMsgid(msgid);
					return true;
				} catch (Exception e) {
					LOGGER.error("留言删除异常：" + e);
				}
				return false;
			}
		});
		if (succeed) {
			// 更新缓存
			CacheKit.put(CacheBean.MESSAGES, CacheBean.MESSAGES, com.xx566.blog.model.Message.dao
					.findMessages4Page(1, 10));
			renderText("操作成功");
		} else {
			renderText("网络异常");
		}
	}
}
